// SwingOSC.stop
SwingOSC.program = "/usr/local/bin/SwingOSC.jar";
SwingOSC.default.options.javaOptions = "-Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
SwingOSC.default.options.javaOptions = "-Dswing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel";
SwingOSC.default.options.javaOptions = "-Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel";
~joyous = LogJoy.new;

RelativeMotion.initClass().start();

Routine { fork {
	SwingOSC.default.boot;
	5.wait;
	"swingosc BOOT".postln;
	s.boot;
	5.wait;
	"server BOOT".postln;
	~joys = ~joyous.sticks.flatten;
	~sticks = 4.collect{ Bus.control };
	~win = Window( "J  O  Y", Rect( 500, 500, 500, 500 ) );
	~win.view.background = Color.new( 0.2, 0.2, 0.2 );
	~sliders = {
		var x0 = 250;
		var y0 = 250;
		var x1 = 250;
		var y1 = 250;

		var img0 = JSCImage.open( "/home/justin/leftHand.png" );
		var img1 = JSCImage.open( "/home/justin/rightHand.png" );
		~win.drawHook = {
			Pen.translate( x0, y0 );
			Pen.image( img0 );
			Pen.translate( x1-x0, y1-y0 );
			Pen.image( img1 );
		};
		[
			{ | x | x0 = x*480; ~win.refresh },
			{ | x | y0 = x*480; ~win.refresh },
			{ | x | x1 = x*480; ~win.refresh },
			{ | x | y1 = x*480; ~win.refresh }
		]
		// var img0 = StaticText( ~win, Rect( x0, y0, 20, 20 ) );
		// var img1 = StaticText( ~win, Rect( x1, y1, 20, 20 ) );

		// var redraw0 = { img0.bounds = Rect( x0, y0, 20, 20 ) };
		// var redraw1 = { img1.bounds = Rect( x1, y1, 20, 20 ) };
		// img0.background = Color.new( 1, 0.2, 0.2 );
		// img0.string = "L";
		// img0.font = Font( "Futura", 18 );
		// img1.background = Color.new( 0.2, 0.2, 1 );
		// img1.string = "R";
		// img1.font = Font( "Futura", 18 );
		// [
		// 	{ | x | x0 = x*480; redraw0.() },
		// 	{ | x | y0 = x*480; redraw0.() },
		// 	{ | x | x1 = x*480; redraw1.() },
		// 	{ | x | y1 = x*480; redraw1.() }
		// ]
	}.value;
	~win.front;
	~rel = [ \x0, \y0, \x1, \y1 ].collect{ | sym, x |
		RelativeMotion(
			{ | v, d, c |
				~sticks[ x ].set( v );
				~sliders[ x ].value( v ) },
			~joys[ x ],
			sym
		);
	};
	SynthDef( \blurg, { | freq = 0.5, amp = 0.5, mod = 0.5, mod2 = 0.5 |
		Out.ar( [ 0, 1 ],
			SinOsc.ar(
				\freq.asSpec.map( Lag.kr( freq ) )
				* SinOsc.ar( \freq.asSpec.map( Lag.kr( mod ) ), 0,
					\freq.asSpec.map( Lag.kr( mod2 ) ) ),
				[ \amp.asSpec.map( Lag.kr( amp ) ),
					\amp.asSpec.map( ( 1 - Lag.kr( amp ) ).abs ) ] ) ) }
	).send(s);
	1.wait;
	~syn = Synth( \blurg );
	[ \freq, \amp, \mod, \mod2 ].do{ | k, i |
		~syn.map( k, ~sticks[ i ] );
	};
} }.play;
// ~syn.free;
/*
Routine{
	~sticks[ 0 ].get{ | v | [ 0, v ].postln };
	0.3.wait;
	~sticks[ 1 ].get{ | v | [ 1, v ].postln };
	0.3.wait;
	~sticks[ 2 ].get{ | v | [ 2, v ].postln };
	0.3.wait;
	~sticks[ 3 ].get{ | v | [ 3, v ].postln };
}.play;
*/
// ~sticks.do{ | s, x | s.get{ | v | [ x, v ].postln } };
